package com.vcsoft.emailresponder.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.vcsoft.emailresponder.util.PropertyRader;

public abstract class AbstractParser<T> extends DefaultHandler {
	
	public abstract Collection<T> parse(NodeList nodeList);
	
	//public abstract T parse(NodeList nodeList);
	
	/**
	 * @param tagName
	 * @return
	 */
	public NodeList getNodeList(String tagName){
		
		if(tagName == null){
			System.out.println("tagName is null");
			return null;
		}
		
		Document doc;
		String xmlRecords = convertXMLFileToString(PropertyRader.getConfigFile());
		NodeList nodeList = null;
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xmlRecords));
			doc = db.parse(is);
			nodeList = doc.getElementsByTagName(tagName);
		} catch (SAXException e) {
		} catch (ParserConfigurationException e) {
		} catch (IOException e) {
		}
		return nodeList;
	}
	
	/**
	 * @param xmlFileName
	 * @return
	 */
	private String convertXMLFileToString(String xmlFileName) {
		
		if(xmlFileName == null){
			System.out.println("xmlFileName is null");
			return null;
		}
		
		StringWriter stw = null;
		try {
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			InputStream inputStream = new FileInputStream(new File(xmlFileName));
			org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
			stw = new StringWriter();
			Transformer serializer = TransformerFactory.newInstance().newTransformer();
			serializer.transform(new DOMSource(doc), new StreamResult(stw));
		} catch (Exception e) {
		}
		return stw.toString();
	}
}
